<?php 
    include_once('../includes/common.inc.php');
    include_once('../dal/bookDAL.php');
    if(check_login()==false){
        header("location:login.php");
        
    }
    $_title ="Thêm sách";
    
    //xu ly form

    $error_message="";
    $class = "";
    $message = "";
    $bookDAL = new BookDAL();
    if(isset($_POST["bookname"]) && isset($_POST["bookcode"]) 
    && isset($_POST["author"]) && isset($_POST["publisher"]) 
    && isset($_POST["detail"]) && isset($_POST["price"]) && isset($_FILES["image"]))
    {      
        //xu ly image
        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $extension = end(explode(".", $_FILES["image"]["name"]));
        if ((($_FILES["image"]["type"] == "image/gif")
        || ($_FILES["image"]["type"] == "image/jpeg")
        || ($_FILES["image"]["type"] == "image/jpg")
        || ($_FILES["image"]["type"] == "image/png"))
        && in_array($extension, $allowedExts))
        {
            if ($_FILES["image"]["error"] > 0)
            {
                echo "<script type='text/javascript'>alert('Lỗi upload: " . $_FILES["image"]["error"] . "');</script>";
            }
            else
            {
        
                if (!file_exists("../images/products/" . $_FILES["image"]["name"]))
                {
                    move_uploaded_file($_FILES["image"]["tmp_name"],"../images/products/" . $_FILES["image"]["name"]);
                    $_POST["image"] = "images/products/" . $_FILES["image"]["name"];
                    $error_message = $bookDAL->insertBook($_POST);
                }
                else
                {
                    $error_message = "File ảnh này đã tồn tại";
                }
            }
        }
        else
        {
            $error_message = "File ảnh này không hợp lệ";
        }
        
        if($error_message == "")
        {
            $class = "message success";
            $message = "Bạn đã thêm sách mới thành công";
        }
        else
        {
            $class = "message error";
            $message = $error_message;
        }
    }

    include_once('../views/admin/header.php');
    include_once('../views/admin/addbook.php');
    

?>